package com.woniu.config;

import com.woniu.handler.*;
import com.woniu.service.impl.SecurityLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityLoginService securityLoginService;
    @Autowired
    private MyLoginSuccessHandler myLoginSuccessHandler;
    @Autowired
    private JWTFilter jwtFilter;

    @Bean
    public PasswordEncoder getPassword(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(securityLoginService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()            //使用自定义登录页面
//            .loginPage("/login.html")//指定自定义的登录页面地址
//            .loginProcessingUrl("/doLogin")//表单提交地址,对应表单action属性
                .successHandler(myLoginSuccessHandler)//注册登录成功处理器
                .failureHandler(new MyLoginFailHandler())   //注册登录失败处理器
                .permitAll();   //已鉴权

        http.exceptionHandling()
                .accessDeniedHandler(new MyNoAuthHandler())      //注册没有权限处理器
                .authenticationEntryPoint(new MyNoLoginHandler());//注册未登录访问资源的处理器

        http.logout()
                .logoutSuccessHandler(new MyLogoutHandler());//注册退出成功处理器

        http.authorizeRequests()
                .anyRequest().authenticated();//所有请求都需要鉴权

        http.addFilterAfter(jwtFilter, UsernamePasswordAuthenticationFilter.class);
        //前后端项目中禁用掉session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.csrf().disable();//关闭跨站脚本攻击
    }
}
